import Vue from 'vue';
import VueRouter from 'vue-router';
import routes from './routes';
import store from '@/store';

Vue.use(VueRouter);

//因为编程式路由导航重复导航的是时候 会报错,我们需要重写push和replace解决这个问题
//1. 保存旧的push方法
const oldPushMethod = VueRouter.prototype.push;
//2. 覆盖原来的push方法 重写push
VueRouter.prototype.push = function(
    location,
    onComplate = () => {},
    onAbort = () => {},
) {
  //内部使用的还是以前的push方法,但是我们给添加了处理异常的回调函数
  return oldPushMethod.call(this, location, onComplate, onAbort);
};

//1. 保存旧的replace方法
const oldReplaceMethod = VueRouter.prototype.replace;
//2. 覆盖原来的push方法 重写push
VueRouter.prototype.replace = function(
    location,
    onComplate = () => {},
    onAbort = () => {},
) {
  //内部使用的还是以前的push方法,但是我们给添加了处理异常的回调函数
  return oldReplaceMethod.call(this, location, onComplate, onAbort);
};

const router = new VueRouter({
  routes,
  mode: 'history',
});

const whiteList = ['login', 'register', 'home'];

router.beforeEach(async(to, from, next) => {
  const token = store.state.user.token;
  const userinfo = store.state.user.userinfo;

  // if logined then reject jump to login page
  if (to.name === 'login' && token) {
    return next('/home');
  }

  // if user profile exist and token exist then you may already logined
  if (userinfo.nickname && token) {
    return next();
  } else {
    await store.dispatch('user/getUserinfo');
  }

  // whiteList
  if (whiteList.includes(to.name)) {
    return next();
  }

  // 未登录
  if (!userinfo.nickname && !token) {
    return next({
      name: 'login',
      query: { redirect: to.name },
    });
  }

  next()

});

export default router;
